package com.android.huimeiqupin.activity.mine;

import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.android.huimeiqupin.R;
import com.android.huimeiqupin.app.BaseActivity;
import com.android.huimeiqupin.model.group.AdPictureData;
import com.android.huimeiqupin.model.group.AdPictureDataCallback;
import com.android.huimeiqupin.model.member.LoginResultData;
import com.android.huimeiqupin.model.member.LoginResultDataCallback;
import com.android.huimeiqupin.model.member.SendCodeData;
import com.android.huimeiqupin.model.member.SendCodeDataCallback;
import com.android.huimeiqupin.utils.ConstantsUrl;
import com.android.huimeiqupin.utils.HttpUtils;
import com.android.huimeiqupin.utils.MyLog;
import com.android.huimeiqupin.utils.ObjectUtils;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class SignActivity extends BaseActivity {


    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.login_radio_login)
    RadioButton loginRadioLogin;
    @BindView(R.id.login_radio_sign)
    RadioButton loginRadioSign;
    @BindView(R.id.login_radio_ll)
    RadioGroup loginRadioLl;
    @BindView(R.id.ll_login_phone)
    EditText llLoginPhone;
    @BindView(R.id.ll_login_pd)
    EditText llLoginPd;
    @BindView(R.id.ll_login)
    LinearLayout llLogin;
    @BindView(R.id.ll_sign_phone)
    EditText llSignPhone;
    @BindView(R.id.ll_sign_code)
    EditText llSignCode;
    @BindView(R.id.ll_sign_code_send)
    TextView llSignCodeSend;
    @BindView(R.id.ll_sign_pd)
    EditText llSignPd;
    @BindView(R.id.ll_sign)
    LinearLayout llSign;
    @BindView(R.id.progress_loading)
    FrameLayout progress_loading;
    @BindView(R.id.login)
    TextView login;
    @BindView(R.id.iv_sign_bg)
    ImageView signBg;

    private boolean networkConnected;
    private TimeCount time;
    private BaseActivity mcontext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign);
        ButterKnife.bind(this);
        mcontext = this;
        initUI();
        time = new TimeCount(60000, 1000);
        getBanner();
    }

    private void getBanner() {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            String address = ConstantsUrl.domain + ConstantsUrl.ADVERTISEPICTURE;
            HashMap<String, String> map = new HashMap<>();
            map.put("typeid","20");
            HttpUtils.get(address, map, dataCallback);
        }
    }

    AdPictureDataCallback dataCallback = new  AdPictureDataCallback() {
        @Override
        public void onError(Call call, Exception e, int id) {
        }

        @Override
        public void onResponse(AdPictureData response, int id) {
            if (response.getData() != null && response.getData().getAd() != null && response.getData().getAd().size() > 0) {
                ObjectUtils.photo2(mcontext, response.getData().getAd().get(0).getPath(), signBg);
            }
        }
    };

    private boolean isCheck = true;

    private void initUI() {
        loginRadioLogin.setChecked(isCheck);
        llLogin.setVisibility(View.VISIBLE);
        loginRadioLl.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                int radioButtonId = radioGroup.getCheckedRadioButtonId();
                if (radioButtonId == R.id.login_radio_login) {
                    isCheck = true;
                    llLogin.setVisibility(View.VISIBLE);
                    llSign.setVisibility(View.GONE);
                    login.setText("登录");
                } else {
                    isCheck = false;
                    llSign.setVisibility(View.VISIBLE);
                    llLogin.setVisibility(View.GONE);
                    login.setText("注册");

                }
            }
        });
    }

    //登录
    private void PostLogin(String phone, String pd) {
        networkConnected = ObjectUtils.isNetworkConnected(this);
        String address = ConstantsUrl.domain + ConstantsUrl.MEMBERORLOGIN;
        HashMap<String, String> map = new HashMap<>();
        MyLog.e("地址", address);
        map.put("username", phone);
        map.put("password", pd);
        if (networkConnected) {
            progress_loading.setVisibility(View.VISIBLE);
            HttpUtils.post(address, map, new LoginResultDataCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    progress_loading.setVisibility(View.GONE);
                }

                @Override
                public void onResponse(LoginResultData response, int id) {
                    progress_loading.setVisibility(View.GONE);
                    if(response == null){
                        return;
                    }
                    if (response.getCode() == 0) {
                        //保存用户数据
                        LoginResultData.DataBean data = response.getData();
                        if(data!=null){
                            PostLoginThree(data.getUNAME(), data.getAvatar(), data.getUID(), data.getUPSW(), data.getZONE(),data.getCITY());
                        }
                    } else {
                        ObjectUtils.toast(SignActivity.this, response.getMsg());
                    }
                }
            });
        } else {
            ObjectUtils.toast(this, "网络连接出错了");
        }

    }

    private void PostSign(String phone, String code, String pd) {
        networkConnected = ObjectUtils.isNetworkConnected(this);
        String address = ConstantsUrl.domain + ConstantsUrl.MEMBERORSIGN;
        MyLog.e("地址", address);
        if (networkConnected) {
            progress_loading.setVisibility(View.VISIBLE);
            HashMap<String, String> map = new HashMap<>();
            map.put("mobile", phone);
            map.put("verifycode", code);
            map.put("password", pd);
            HttpUtils.post(address, map, new LoginResultDataCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {

                    progress_loading.setVisibility(View.GONE);
                }

                @Override
                public void onResponse(LoginResultData response, int id) {
                    progress_loading.setVisibility(View.GONE);
                    if(response == null){
                        return;
                    }
                    if (response.getCode() == 0) {
                        //保存用户数据
                        LoginResultData.DataBean data = response.getData();
                        if(data!=null){
                            PostLoginThree(data.getUNAME(), data.getAvatar(), data.getUID(), data.getUPSW(), data.getZONE(),data.getCITY());
                        }
                    } else {
                        ObjectUtils.toast(SignActivity.this, response.getMsg());
                    }
                }
            });
        } else {
            ObjectUtils.toast(this, "网络连接出错了");
        }
    }


    //发送验证码
    private void SendCode(String phone) {
        String address = ConstantsUrl.domain + ConstantsUrl.MEMBERORSENDMESSAGE;
        HashMap<String, String> map = new HashMap<>();
        map.put("mobile", phone);
//        map.put("act", "sms_register");
        networkConnected = ObjectUtils.isNetworkConnected(this);
        if (networkConnected) {
            progress_loading.setVisibility(View.VISIBLE);
            HttpUtils.post(address, map, new SendCodeDataCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {

                    progress_loading.setVisibility(View.GONE);
                }

                @Override
                public void onResponse(SendCodeData response, int id) {
                    progress_loading.setVisibility(View.GONE);
                    if(response == null){
                        return;
                    }
                    ObjectUtils.toast(SignActivity.this, response.getMsg());
                    if (response.getCode() == 0) {
                        time.start();
                    }
                }
            });
        } else {
            ObjectUtils.toast(this, "网络连接出错了");
        }
    }

    @OnClick({R.id.back, R.id.ll_sign_code_send, R.id.login})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.ll_sign_code_send:
                String sign_phone = llSignPhone.getText().toString().trim();
                if ("".equals(sign_phone)) {
                    ObjectUtils.toast(this, "请输入手机号码");
                    return;
                }
                SendCode(sign_phone);
                break;
            case R.id.login:
                if (isCheck) {
                    String lgphone = llLoginPhone.getText().toString().trim();
                    String lgpd = llLoginPd.getText().toString().trim();
                    if ("".equals(lgphone)) {
                        ObjectUtils.toast(this, "请输入账号");
                        return;
                    }
                    if ("".equals(lgpd)) {
                        ObjectUtils.toast(this, "请输入密码");
                        return;
                    }
                    PostLogin(lgphone, lgpd);

                } else {
                    String sgphone = llSignPhone.getText().toString().trim();
                    String sgcode = llSignCode.getText().toString().trim();
                    String sgpd = llSignPd.getText().toString().trim();
                    if ("".equals(sgphone)) {
                        ObjectUtils.toast(this, "请输入手机号");
                        return;
                    }
                    if ("".equals(sgcode)) {
                        ObjectUtils.toast(this, "请输入验证码");
                        return;
                    }
                    if ("".equals(sgpd)) {
                        ObjectUtils.toast(this, "请设置密码");
                        return;
                    }
                    PostSign(sgphone, sgcode, sgpd);
                }
                break;
        }
    }

    //登录并保存
    private void PostLoginThree(String uname, String avatar, String uid, String upsw,String zone,String city) {
        SharedPreferences sp = getSharedPreferences(ConstantsUrl.USERDATA, 0);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString(ConstantsUrl.USERDATA_NAME, uname);
        edit.putString(ConstantsUrl.USERDATA_AVATAR, avatar);
        edit.putString(ConstantsUrl.USERDATA_UID, uid);
        edit.putString(ConstantsUrl.USERDATA_UPSW, upsw);
        edit.putInt(ConstantsUrl.USERDATA_TYPE, 0);
        edit.putString(ConstantsUrl.USERDATA_ZONE,zone);
        edit.putString(ConstantsUrl.USERDATA_CITY,city);
        edit.commit();
        ObjectUtils.toast(SignActivity.this, "登录成功");
        LoginActivity.intance.finish();
        finish();
    }

    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            llSignCodeSend.setText("重新获取验证码");
            llSignCodeSend.setTextColor(Color.parseColor("#ffffff"));
            llSignCodeSend.setBackgroundResource(R.drawable.corner_red_bg);
            llSignCodeSend.setClickable(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            llSignCodeSend.setClickable(false);// 防止重复点击
            llSignCodeSend.setTextColor(Color.parseColor("#5a5a5a"));
            llSignCodeSend.setBackgroundResource(R.drawable.corner_gray_bg);
            llSignCodeSend.setText("重新发送(" + millisUntilFinished / 1000 + ")秒");
        }
    }
}
